//
//  YFComposeViewController.swift
//  微博
//
//  Created by 余仿 on 16/4/15.
//  Copyright © 2016年 YF. All rights reserved.
//

import UIKit

import SnapKit

import SVProgressHUD

/// 发送微博的控制器

class YFComposeViewController: UIViewController {

    //MARK:文本框
    private lazy var msgView:YFTextView = {

        let t = YFTextView()

        t.textColor = UIColor.darkGrayColor()

        t.font = UIFont.systemFontOfSize(18)

        t.backgroundColor = UIColor(white: 0.95, alpha: 1)

        t.alwaysBounceVertical = true

        t.keyboardDismissMode = .OnDrag

//        t.becomeFirstResponder()

        t.delegate = self

        return t

    }()

    //MARK:标题
    private var titleView:UIView?

    //MARK:监听字数的文本
    private lazy var wordLabel:UILabel = UILabel(title: "还可以输入140字", fontSize: 18, fontColor: UIColor.blueColor())

    //MARK:占位文本
    private lazy var tipLabel:UILabel = UILabel(title: "分享新鲜事...", fontSize: 18, fontColor: UIColor.lightGrayColor())

    //MARK:底部工具条
    private lazy var bottomBar:UIToolbar = {

        let array = [
            ["imageName":"compose_toolbar_picture","action":"uploadImage"],
            ["imageName":"compose_mentionbutton_background","action":"uploadImage"],
            ["imageName":"compose_trendbutton_background","action":"uploadImage"],
            ["imageName":"compose_emoticonbutton_background","action":"useCustomEmotionKeyBoard"],
            ["imageName":"compose_add_background","action":"uploadImage"],
        ]

        let t = UIToolbar()

        t.items = [UIBarButtonItem]()

        for i in 0..<array.count{

            /*
            Cannot convert value of type 'NSObject -> () -> YFComposeViewController' to expected argument type 'AnyObject?'
            */
            //在这个方法中根本不能访问
            //获取字典中的数据
            let bottomItemContent = array[i]

            let imageName = bottomItemContent["imageName"]!

            let action = bottomItemContent["action"]!

            let selector = Selector(action)
            //创建五个按钮
            let item:UIBarButtonItem = UIBarButtonItem(imageName: imageName, title: nil, target: self, action: selector)

            print(t.items?.count)

            t.items?.append(item)

            print(t.items?.count)

            let space = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)

            if i != array.count - 1{

                t.items?.append(space)
            }
        }
        return t
    }()

    //图片选择控制器
    private lazy var pictureSelector:YFSelectImageController = YFSelectImageController()

    //MARK:

    override func viewDidLoad() {

        view.backgroundColor = UIColor.whiteColor()

        setupUI()

        registerNotification()
    }

    //MARK:设置UI
    private  func setupUI(){

        //设置导航条
        setupNavBarButtonItem()

        //设置文本框
        view.addSubview(msgView)

        view.addSubview(wordLabel)

        view.addSubview(bottomBar)

        msgView.addSubview(tipLabel)

        setupPictureSelector()

        //布局文本框
        msgView.snp_makeConstraints { (make) -> Void in
            make.top.left.right.equalTo(self.view)
            make.height.equalTo(screenHeigth / 3)
        }

        //布局字数统计文字
        wordLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(msgView.snp_bottom).offset(statusCellMargin)
            make.left.equalTo(self.view.snp_left).offset(statusCellMargin)
        }

        //设置占位提示文字
        tipLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(msgView.snp_top).offset(8)
            make.left.equalTo(msgView.snp_left).offset(5)
        }

        //设置底部工具条
        bottomBar.snp_makeConstraints { (make) -> Void in
            make.left.right.bottom.equalTo(self.view)
        }

        //布局titleView
        titleView?.snp_makeConstraints(closure: { (make) -> Void in
            make.centerX.equalTo(navigationController!.navigationBar.snp_centerX)
            make.top.equalTo(navigationController!.navigationBar.snp_top).offset(0)
        })
    }

    //MARK:设置图片选择视图
    func setupPictureSelector(){

        self.addChildViewController(pictureSelector)

        let pictureSelectorView = pictureSelector.view

        view.addSubview(pictureSelectorView)

        pictureSelectorView.snp_makeConstraints { (make) -> Void in
            make.left.right.bottom.equalTo(self.view)
            make.height.equalTo(0)
        }

    }

    //MARK:设置导航条
    private  func setupNavBarButtonItem(){

        //关闭按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: nil, title: "关闭", target: self, action: "closeDidClick")

        //发送按钮
        setupSendButton()

        //中间的标题
        titleView = setupTitleView()
        navigationController?.navigationBar.addSubview(titleView!)
    }

    //MARK:设置titleView
    private func setupTitleView() -> UIView{

        let titleview = UIView()
        //添加两个label
        let bigTitle = UILabel(title: "发微博", fontSize: 20, fontColor: UIColor.darkGrayColor())

        let smallTitle = UILabel(title: YFViewModel.sharedViewModels.userAccount?.name ?? "", fontSize: 15, fontColor: UIColor.grayColor())

        //设置发微博为粗体
        bigTitle.font = UIFont(name: "TrebuchetMS-Bold", size: 19)

        titleview.addSubview(bigTitle)
        titleview.addSubview(smallTitle)

        bigTitle.snp_makeConstraints(closure: { (make) -> Void in

            make.top.equalTo(titleview.snp_top)
            make.centerX.equalTo(titleview.snp_centerX)

        })

        smallTitle.snp_makeConstraints(closure: { (make) -> Void in
            make.top.equalTo(bigTitle.snp_bottom)
            make.centerX.equalTo(titleview.snp_centerX)
        })

        return titleview
    }

    //MARK:设置发送按钮
    private func setupSendButton(){
        //右边是发送
        let btn = UIButton(imageName: nil, title: "发送", target: self, action: "sendDidClick",bgImage: "common_button_orange")

        btn.bounds = CGRect(x: 0, y: 0, width: 45, height: 30)

        //设置btn的禁用是没有效果的,需要设置创建好的UIBarButtonItem的禁用
//        btn.enabled = false

        //设置背景图片
        btn.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: .Disabled)

        //设置文字颜色
        btn.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        btn.setTitleColor(UIColor.darkGrayColor(), forState: .Disabled)

        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: btn)
        //需要写在下面,当按钮还没有创建,等于设置nil的禁用,没有效果
        navigationItem.rightBarButtonItem?.enabled = false

    }

    //MARK:关闭按钮的点击事件
    @objc private func closeDidClick(){

        dismissViewControllerAnimated(true, completion: nil)

    }

    //MARK:发送按钮的点击事件
    @objc private  func sendDidClick(){

        print("点击了发送按钮")

        //显示正在发布
        SVProgressHUD.show()

        //获取文本框中的文本
        let msg = msgView.showFullText()


        let token = (YFViewModel.sharedViewModels.userAccount?.access_token)!

        //        guard  let token = YFViewModel.sharedViewModels.userAccount?.access_token else{
        //            return
        //        }

        //发布微博
        HMNetworkTools.sharedTools.uploadStatus(token, status: msg,images:pictureSelector.imageList) { (result, error) -> () in

            SVProgressHUD.dismiss()

            if error != nil{

                print(error)

                SVProgressHUD.showErrorWithStatus("发送失败")

                return
            }

            SVProgressHUD.showSuccessWithStatus("发布成功")

            // 自动关闭当前界面
            self.closeDidClick()
        }
    }

    //MARK:注册通知
    private func registerNotification(){

        NSNotificationCenter.defaultCenter().addObserver(self, selector: "beginEdit:", name: UITextViewTextDidChangeNotification, object: msgView)

        NSNotificationCenter.defaultCenter().addObserver(self, selector:"updateBottomBarLocation:" , name: UIKeyboardWillChangeFrameNotification, object: nil)
    }

    //MARK:根据键盘的位置,修改bottomBar的位置
    //根据键盘的Y值的改变修改tabBar的底部约束,
    //MARK:监听键盘的位置改变
    @objc private func updateBottomBarLocation(notification:NSNotification){

        print(notification)

        //        1.取出键盘将要改变位置时的Y值
        let value = notification.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue

        //        2.将NSValue转成结构体

        let rect = value.CGRectValue()

        //        3.取出结构体中的Y值
        let keyBoardY = rect.origin.y

        bottomBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(self.view.snp_bottom).offset(keyBoardY - screenHeigth)
        }
    }

    //MARK:监听文本框
    func beginEdit(info:NSNotification){

        //发送按钮不禁用
        navigationItem.rightBarButtonItem!.enabled = msgView.hasText()

        //获取输入文字字数
        let wordCount = msgView.text.characters.count

        //将已输入的字数和140比较
        if wordCount > 140{
            
            wordLabel.textColor = UIColor.redColor()
            
            wordLabel.text = "已超出\(wordCount - 140)个字"
            
            navigationItem.rightBarButtonItem!.enabled = false
            
        }else if (wordCount < 140){
            
            wordLabel.textColor = UIColor.blueColor()
            
            navigationItem.rightBarButtonItem!.enabled = true
            
            wordLabel.text = "还可以输入\(140 - wordCount)个字"
        }
        
        //如果小于140字,提示,还可以输入xx个字
        //如果大于140字,提示,已超出xx字
    }

    //MARK:上传图片
    @objc private func uploadImage(){
//        1.弹出图片控制器 
//    修改布局


    pictureSelector.view.snp_updateConstraints { (make) -> Void in

        make.height.equalTo(screenHeigth / 3 * 2)

    }

    }

    //MARK:使用自定义表情键盘
    @objc private func useCustomEmotionKeyBoard(){

        print(msgView.inputView)

        if  !msgView.isFirstResponder(){
            msgView.becomeFirstResponder()
        }

        msgView.inputView = msgView.inputView == nil ? YFEmojiKeyBoardView():nil
//        msgView.inputView = YFEmojiKeyBoardView()

        msgView.reloadInputViews()

        //添加通知的接收者
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "insertEmotion:", name: YFEmotionBtnDidClick, object: nil)
    }

    deinit{

        NSNotificationCenter.defaultCenter().removeObserver(self, name: YFEmotionBtnDidClick, object: nil)
    }

    @objc private func insertEmotion(nofi:NSNotification){

        print(nofi.object)
        //        根据字典获取图片路径
        guard let emoji = nofi.object as? YFEmoji else{

            print("模型为空,或者参数无法转换成表情模型")
            return
        }

        msgView.insertImageWithName(emoji)
    }
}

// MARK: - 文本框的代理方法
extension YFComposeViewController:UITextViewDelegate{
    
    func textViewDidChange(textView: UITextView) {
        //当文字开始改变,隐藏提示label,并且发送按钮可用
        navigationItem.rightBarButtonItem!.enabled = textView.hasText()

//        let str = msgView.showFullText()

        tipLabel.hidden = textView.hasText()
    }
}
